package cn.labelnet.android.roomdb.main.adapter

import android.support.v7.widget.AppCompatImageView
import android.support.v7.widget.AppCompatTextView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.labelnet.android.roomdb.R
import cn.labelnet.android.roomdb.base.config.MainData

/**
 * Created by yuan on 02/08/2017.
 * 主页 adapter
 */
class MainAdapter(onMainAdapterItemClick: OnMainAdapterItemClick) : RecyclerView.Adapter<MainAdapter.MainViewHolder>() {

    /**
     * 基本数据
     */
    var datas = ArrayList<MainData>()
    var onMainAdapterItemClick: OnMainAdapterItemClick? = null

    init {
        this.onMainAdapterItemClick = onMainAdapterItemClick
    }

    /**
     * 添加数据
     */
    fun addDatas(datas: ArrayList<MainData>) {
        if (datas.isEmpty()) {
            return
        }
        this.datas.addAll(datas)
        this.notifyItemRangeInserted(itemCount - datas.size, datas.size)
    }

    /**
     * 清除数据
     */
    fun clearDatas() {
        if (this.datas.isNotEmpty()) {
            this.datas.clear()
            this.notifyDataSetChanged()
        }
    }

    override fun onBindViewHolder(holder: MainViewHolder?, position: Int) {
        val mainData = datas[position]
        holder!!.tvTitle.text = mainData.title
        holder.ivImage.setImageDrawable(mainData.icon)
        holder.itemView.setOnClickListener { v -> this.onMainAdapterItemClick?.onItemClick(mainData.type) }
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MainViewHolder {
        val view = LayoutInflater.from(parent!!.context).inflate(R.layout.activity_main_item, null, false)
        return MainViewHolder(view)
    }

    override fun getItemCount(): Int {
        return this.datas.size
    }

    /**
     * 内部类 viewHolder
     */
    class MainViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvTitle: AppCompatTextView = itemView.findViewById<AppCompatTextView>(R.id.tvTitle)
        val ivImage: AppCompatImageView = itemView.findViewById<AppCompatImageView>(R.id.ivImage)
    }

    /**
     * 点击事件
     * onItemClick
     */
    interface OnMainAdapterItemClick {
        fun onItemClick(type: Int)
    }
}
